package com.jwcao.common.cast.operation.access.field;

import com.jwcao.common.cast.Cast;
import com.jwcao.common.cast.context.CastContext;
import com.jwcao.common.cast.annotation.CastField;
import com.jwcao.common.cast.operation.CastFlow;
import com.jwcao.common.scan.object.ScanField;
import java.util.Map;

/**
 * name: FieldAccessOperation description: TODO
 *
 * @author caojingwei date: 2023/3/23 16:13
 */
public class CastFieldAccessOperation extends FieldAccessOperation {

    protected final CastField castField;

    protected final String fieldCastId;

    public CastFieldAccessOperation(CastField castField, ScanField sourceField,
        ScanField targetField) {
        super(targetField,sourceField);
        this.castField = castField;
        if (castField == null) {
            this.fieldCastId = Cast.DEFAULT_ID;
        } else {
            this.fieldCastId = castField.childId();
        }
    }

    @Override
    public Object execute(Object object) {
        return sourceField.get(object);
    }


    public CastFieldAccessOperation flush() {

        if (sourceField.equalType(targetField)) {
            // 类型一样，直接忽略
            return this;
        }

        Class sourceFieldType = sourceField.getFieldType();
        Class targetFieldType = targetField.getFieldType();

        //1. sourceField 是泛型
        if (sourceField.isAbstractOrInterface()) {
            Map<Class, CastFlow> castFlowMap = CastContext.getCastFlowMapBySubClass(sourceFieldType, targetFieldType,
                fieldCastId);
            return new GenericsAccessOperation(castField, sourceField, targetField, castFlowMap);
        }

        //2. 如果是明确类型
        CastFlow castFlow = CastContext.getCastFlowByClass(sourceFieldType,
            targetField.getFieldType(), fieldCastId);
        return new RecursionAccessOperation(castField, sourceField, targetField, castFlow);
    }


}
